using System.Threading.Tasks;
using Ant.DbServiceInterface;
using Ant.Dto.StoreDto;
using Ant.EntityFrameworkCore.Model;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Authorization;

namespace Ant.Service.Conntroller
{
    [Route("ant/{controller}/")]
    public class StoreController : Controller
    {
        private readonly IStoreDataService _dbServiece;
        private readonly IMapper _mapper;

        public StoreController(IStoreDataService dbService, IMapper mapper)
        {
            this._dbServiece = dbService;
            this._mapper = mapper;
        }

        [Route("{action}")]
        [HttpGet]
        public async Task<IActionResult> GetStore()
        {
            var res = await _dbServiece.GetAllStore();
            var data = _mapper.Map<ICollection<GetStoreDto>>(res);
            if (data.Count == 0)
            {
                return BadRequest("没有数据");
            }
            return Ok(data);
        }

        [Route("{storeID}/{action}")]
        [HttpGet]
        public async Task<IActionResult> GetCommodityType([FromRoute] int storeID)
        {
            var res = await _dbServiece.GetCommodityType(storeID);
            if (res.Count == 0)
            {
                return BadRequest("没有数据");
            }
            return Ok(res);
        }

        [Route("{storeID}/{action}")]
        [HttpGet]
        public async Task<IActionResult> GetCommodity([FromRoute] int storeID,
        [FromQuery] int pageSize,
        [FromQuery] int current,
        [FromQuery] string key
        )
        {
            if (pageSize == 0) pageSize = 10;
            if (current == 0) current = 1;
            var res = await _dbServiece.GetCommodity(storeID, pageSize, current, key);
            if (res.Count == 0)
            {
                return BadRequest("没有数据");
            }
            return Ok(new GetCommodityDto() { Count = res.Count, PageSize = pageSize, Current = current, Data = _mapper.Map<ICollection<CommodityDto>>(res.Skip((current - 1) * pageSize).Take(pageSize).ToList()) });
        }

        [Route("{storeID}/{action}")]
        [HttpGet]
        public async Task<IActionResult> SearchCommodity([FromRoute] int storeID, [FromQuery] string key)
        {
            var data = await _dbServiece.SearchCommodityForStore(storeID, key);
            if (data == null)
            {
                return BadRequest("无数据");
            }
            else
            {
                return Ok(_mapper.Map<ICollection<CommodityDto>>(data));
            }
        }

        [HttpGet]
        [Route("{storeID}/{action}")]
        public async Task<IActionResult> GetTable([FromRoute] int storeID)
        {
            var data = await _dbServiece.GetCommodity(storeID);
            var fileName = Guid.NewGuid();
            string path = AppContext.BaseDirectory + fileName.ToString() + ".csv";
            if (!(System.IO.File.Exists(path)))
            {
                System.IO.File.Delete(path);
            }
            System.IO.FileStream memStream = new System.IO.FileStream(path, FileMode.OpenOrCreate);
            memStream.Write(Encoding.UTF8.GetBytes("编号,名称,类型,售价,单位,条码,规格\n"));
            foreach (var item in data)
            {
                string row = $"{item.Cid},{item.Cname},{item.Ctype},{item.Price},{item.Unit},{item.BarCode},{item.Specification}\n";
                memStream.Write(Encoding.UTF8.GetBytes(row));
            }
            Response.Headers.Add("Content-Type","application/octet-stream");
            Response.Headers.Add("Content-Disposition", $"attachment;filename={fileName.ToString()}.csv");
            memStream.Close();
            System.IO.FileStream read = new FileStream(path, FileMode.Open);
            
            return Ok(read);

            // System.IO.File.Delete(path);
            // new MemoryStream()
            // var stream = new FileStream(path, FileMode.Open);
        }

        [Route("{storeID}/{action}")]
        [HttpGet]
        public IActionResult GetHotCommodity([FromRoute] int storeID)
        {
            return Ok(_dbServiece.GetHotCommidit(storeID));
        }


        [Route("{action}")]
        [HttpPost]
        public IActionResult AddStore([FromBody] AddStoreDto addStoreDto)
        {
            var data = _mapper.Map<StoreInfo>(addStoreDto);
            var res = _dbServiece.AddStore(data);
            if (res!=-1)
            {
                return Ok(res);
            }
            else
            {
                return BadRequest("添加失败");
            }
        }

        [Route("{storeID}/{action}")]
        [HttpPost]
        public IActionResult AddCommodityType([FromRoute] int storeID, [FromBody] AddCommodityTypeDto addComTypeDto)
        {
            addComTypeDto.StoreId = storeID;
            var data = _mapper.Map<CommodityType>(addComTypeDto);
            if (_dbServiece.AddCommodityType(data))
            {
                return Ok();
            }
            else
            {
                return BadRequest("添加失败");
            }
        }

        /// <summary>
        /// 商店添加新商品
        /// </summary>
        /// <param name="storeID"></param>
        /// <param name="comDto"></param>
        /// <returns></returns>
        [Route("{storeID}/{action}")]
        [HttpPost]
        [Authorize(Roles = "Admin,Temp,Manager")]
        public IActionResult AddCommodity([FromRoute] int storeID, [FromBody] AddCommodityDto comDto)
        {
            comDto.StoreId = storeID;
            var data = _mapper.Map<CommodityInfo>(comDto);
            if (_dbServiece.AddCommodity(data))
            {
                return Ok();
            }
            else
            {
                return BadRequest("添加失败");
            }
        }

        [Route("{storeID}/{action}")]
        [HttpPut]
        [Authorize(Roles = "Admin,Clerk,Manager")]
        public IActionResult UpdateCommodity([FromRoute] int storeID, [FromBody] UpdataCommodityDto dto)
        {

            if (_dbServiece.UpdateCommodity(storeID, dto))
            {
                return Ok();
            }
            return BadRequest();
        }


    }
}